package com.wdl.fm.system.user.controller;

import com.wdl.fm.common.constants.GlobalConstant;
import com.wdl.fm.common.controller.BaseController;
import com.wdl.fm.system.user.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by Administrator on 2017/6/6.
 */
@Controller
@RequestMapping("/admin/login")
public class LoginController extends BaseController {

    @Autowired
    private UserService userService;

    /**
     * 展示登录界面
     *
     * @return
     */
    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String showLoginView() {
        return "admin/login";
    }

    /**
     * 登录
     *
     * @param request
     */
    @RequestMapping(value = "/", method = RequestMethod.POST)
    public String doLogin(Model model, HttpServletRequest request) {
        String indexUrl = "redirect:/page/admin/index/";
        String loginUrl = "redirect:/page/admin/login/";

        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String remberMe = request.getParameter("remberMe");

        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(username, password);
        usernamePasswordToken.setRememberMe("on".equals(remberMe));

        Subject curUser = SecurityUtils.getSubject();

        try {
            curUser.login(usernamePasswordToken);
        } catch (AuthenticationException exception) {
            model.addAttribute("error", exception.getMessage());
            return loginUrl;
        }

        return indexUrl;
    }

    /**
     * 展示登录界面
     *
     * @return
     */
    @RequestMapping(value = "/logout", method = RequestMethod.GET)
    public String logout(HttpServletRequest request) {
        SecurityUtils.getSubject().logout();
        return "admin/login";
    }
}
